<template>
  <div class="my-roles-page">
    <div class="container">
      <div class="page-header">
        <h1 class="page-title">我的角色</h1>
        <p class="page-subtitle">管理你创建的AI角色和收藏的角色</p>
        <router-link to="/create-role" class="create-btn">创建新角色</router-link>
      </div>
      
      <div class="tab-container">
        <div class="tabs">
          <button 
            :class="['tab', { active: activeTab === 'created' }]"
            @click="setActiveTab('created')"
          >
            我创建的
          </button>
          <button 
            :class="['tab', { active: activeTab === 'favorite' }]"
            @click="setActiveTab('favorite')"
          >
            我收藏的
          </button>
        </div>
      </div>
      
      <div v-if="loading" class="loading-grid">
        <div v-for="i in 6" :key="i" class="role-card skeleton">
          <div class="skeleton-avatar"></div>
          <div class="skeleton-content">
            <div class="skeleton-title"></div>
            <div class="skeleton-desc"></div>
          </div>
        </div>
      </div>
      
      <div v-else-if="roles.length === 0" class="empty-state">
        <div class="empty-icon">🎭</div>
        <h3 v-if="activeTab === 'created'">还没有创建角色</h3>
        <h3 v-else>还没有收藏角色</h3>
        <p v-if="activeTab === 'created'">创建你的第一个AI角色，开始精彩的对话体验</p>
        <p v-else>去角色广场发现并收藏你喜欢的角色吧</p>
        <router-link v-if="activeTab === 'created'" to="/create-role" class="create-btn">创建角色</router-link>
        <router-link v-else to="/role-square" class="create-btn">去角色广场</router-link>
      </div>
      
      <div v-else class="roles-grid">
        <div v-for="role in roles" :key="role.id" class="role-card">
          <div class="role-avatar">
            <img v-if="role.avatarUrl" :src="role.avatarUrl" :alt="role.name" />
            <div v-else class="avatar-placeholder">{{ role.name.charAt(0) }}</div>
            <div class="role-status" :class="role.status.toLowerCase()">
              {{ getStatusText(role.status) }}
            </div>
          </div>
          
          <div class="role-info">
            <h3 class="role-name">{{ role.name }}</h3>
            <p class="role-desc">{{ role.description || '暂无描述' }}</p>
            
            <div class="role-stats">
              <div class="stat">
                <span class="stat-icon">💬</span>
                <span class="stat-value">{{ role.usageCount || 0 }}</span>
                <span class="stat-label">使用</span>
              </div>
              <div class="stat">
                <span class="stat-icon">⭐</span>
                <span class="stat-value">{{ role.averageRating || 0 }}</span>
                <span class="stat-label">评分</span>
              </div>
              <div class="stat">
                <span class="stat-icon">📅</span>
                <span class="stat-value">{{ formatDate(role.createdAt) }}</span>
              </div>
            </div>
          </div>
          
          <div class="role-actions">
            <button class="action-btn primary" @click="startChat(role)">对话</button>
            <button class="action-btn" @click="viewDetails(role)">详情</button>
            <button v-if="activeTab === 'created'" class="action-btn" @click="editRole(role)">编辑</button>
            <button v-if="activeTab === 'created' && role.privacy === 'PRIVATE'" class="action-btn publish" @click="publishToSquare(role)">发布到广场</button>
            <button v-if="activeTab === 'created' && role.privacy === 'PUBLIC'" class="action-btn unpublish" @click="unpublishFromSquare(role)">停止发布</button>
            <button v-if="activeTab === 'created'" class="action-btn danger" @click="deleteRole(role)">删除</button>
            <button v-if="activeTab === 'favorite'" class="action-btn danger" @click="removeFavorite(role)">取消收藏</button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'

const router = useRouter()
const loading = ref(false)
const roles = ref([])
const activeTab = ref('created')

const loadMyRoles = async () => {
  loading.value = true
  try {
    const token = localStorage.getItem('auth_token')
    if (!token) {
      router.push('/login')
      return
    }
    
    const endpoint = activeTab.value === 'created' ? '/api/roles/my' : '/api/roles/favorites'
    const res = await fetch(endpoint, {
      headers: { 'Authorization': `Bearer ${token}` }
    })
    const data = await res.json()
    if (data.code === 0) {
      // 后端返回的是分页数据，角色列表在records字段中
      roles.value = data.data?.records || []
      console.log('获取到的角色列表:', roles.value)
    } else {
      console.error('获取角色列表失败:', data.message)
    }
  } catch (e) {
    console.error('加载我的角色失败', e)
  } finally {
    loading.value = false
  }
}

const setActiveTab = (tab) => {
  activeTab.value = tab
  loadMyRoles()
}

const getStatusText = (status) => {
  const statusMap = {
    'PUBLISHED': '已发布',
    'DRAFT': '草稿',
    'PENDING': '待审核',
    'REJECTED': '已拒绝'
  }
  return statusMap[status] || status
}

const formatDate = (dateStr) => {
  if (!dateStr) return ''
  const date = new Date(dateStr)
  const now = new Date()
  const diffTime = Math.abs(now - date)
  const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24))
  
  if (diffDays === 1) return '昨天'
  if (diffDays < 7) return `${diffDays}天前`
  if (diffDays < 30) return `${Math.ceil(diffDays / 7)}周前`
  return date.toLocaleDateString()
}

const startChat = (role) => {
  router.push(`/chat/${role.id}`)
}

const editRole = (role) => {
  router.push(`/edit-role/${role.id}`)
}

const viewDetails = (role) => {
  router.push(`/role-details/${role.id}`)
}

const publishToSquare = async (role) => {
  if (!confirm(`确定要将角色"${role.name}"发布到角色广场吗？发布后其他用户可以看到并使用这个角色。`)) {
    return
  }
  
  try {
    const token = localStorage.getItem('auth_token')
    const res = await fetch(`/api/roles/${role.id}/publish`, {
      method: 'POST',
      headers: { 'Authorization': `Bearer ${token}` }
    })
    
    const data = await res.json()
    if (data.code === 0) {
      // 更新角色隐私状态
      role.privacy = 'PUBLIC'
      alert('角色已成功发布到角色广场！')
    } else {
      alert('发布失败：' + data.message)
    }
  } catch (e) {
    console.error('发布角色失败', e)
    alert('发布失败，请重试')
  }
}

const unpublishFromSquare = async (role) => {
  if (!confirm(`确定要停止发布角色"${role.name}"吗？停止发布后其他用户将无法在角色广场看到这个角色。`)) {
    return
  }
  
  try {
    const token = localStorage.getItem('auth_token')
    const res = await fetch(`/api/roles/${role.id}/unpublish`, {
      method: 'POST',
      headers: { 'Authorization': `Bearer ${token}` }
    })
    
    const data = await res.json()
    if (data.code === 0) {
      // 更新角色隐私状态
      role.privacy = 'PRIVATE'
      alert('角色已停止发布！')
    } else {
      alert('停止发布失败：' + data.message)
    }
  } catch (e) {
    console.error('停止发布角色失败', e)
    alert('停止发布失败，请重试')
  }
}

const deleteRole = async (role) => {
  if (!confirm(`确定要删除角色"${role.name}"吗？此操作不可撤销。`)) {
    return
  }
  
  try {
    const token = localStorage.getItem('auth_token')
    const res = await fetch(`/api/roles/${role.id}`, {
      method: 'DELETE',
      headers: { 'Authorization': `Bearer ${token}` }
    })
    
    const data = await res.json()
    if (data.code === 0) {
      roles.value = roles.value.filter(r => r.id !== role.id)
    } else {
      alert('删除失败：' + data.message)
    }
  } catch (e) {
    console.error('删除角色失败', e)
    alert('删除失败，请重试')
  }
}

onMounted(() => {
  loadMyRoles()
})
</script>

<style scoped>
.my-roles-page {
  height: 100%;
  background: #f8fafc;
  padding: 40px 0;
  overflow-y: auto;
}

.container {
  width: 100%;
  padding: 0 32px;
}

.page-header {
  text-align: center;
  margin-bottom: 40px;
}

.page-title {
  font-size: 2.5rem;
  font-weight: 700;
  color: #1f2937;
  margin-bottom: 8px;
}

.page-subtitle {
  font-size: 1.125rem;
  color: #6b7280;
  margin-bottom: 24px;
}

.tab-container {
  margin-bottom: 32px;
}

.tabs {
  display: flex;
  gap: 8px;
  border-bottom: 2px solid #e5e7eb;
}

.tab {
  padding: 12px 24px;
  background: none;
  border: none;
  color: #6b7280;
  cursor: pointer;
  font-weight: 500;
  border-bottom: 2px solid transparent;
  transition: all 0.2s;
}

.tab:hover {
  color: #374151;
}

.tab.active {
  color: #667eea;
  border-bottom-color: #667eea;
}

.create-btn {
  display: inline-flex;
  align-items: center;
  gap: 8px;
  padding: 12px 24px;
  background: linear-gradient(135deg, #667eea, #764ba2);
  color: white;
  text-decoration: none;
  border-radius: 8px;
  font-weight: 600;
  transition: all 0.2s;
}

.create-btn:hover {
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(102, 126, 234, 0.3);
}

.roles-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(320px, 1fr));
  gap: 24px;
}

.role-card {
  background: white;
  border-radius: 16px;
  padding: 24px;
  box-shadow: 0 4px 6px rgba(0,0,0,0.05);
  border: 1px solid #e5e7eb;
  transition: all 0.3s;
}

.role-card:hover {
  transform: translateY(-4px);
  box-shadow: 0 12px 24px rgba(0,0,0,0.1);
  border-color: #667eea;
}

.role-avatar {
  position: relative;
  width: 80px;
  height: 80px;
  border-radius: 50%;
  margin-bottom: 16px;
  overflow: hidden;
  background: linear-gradient(135deg, #667eea, #764ba2);
  display: flex;
  align-items: center;
  justify-content: center;
}

.role-avatar img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.avatar-placeholder {
  color: white;
  font-size: 32px;
  font-weight: 600;
}

.role-status {
  position: absolute;
  top: -4px;
  right: -4px;
  padding: 4px 8px;
  border-radius: 12px;
  font-size: 12px;
  font-weight: 500;
  color: white;
}

.role-status.published {
  background: #10b981;
}

.role-status.draft {
  background: #f59e0b;
}

.role-status.pending {
  background: #3b82f6;
}

.role-name {
  font-size: 1.25rem;
  font-weight: 600;
  color: #1f2937;
  margin-bottom: 8px;
}

.role-desc {
  color: #6b7280;
  line-height: 1.5;
  margin-bottom: 16px;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.role-stats {
  display: flex;
  gap: 16px;
  margin-bottom: 16px;
}

.stat {
  display: flex;
  align-items: center;
  gap: 4px;
  color: #6b7280;
  font-size: 14px;
}

.stat-icon {
  font-size: 16px;
}

.stat-value {
  font-weight: 500;
}

.stat-label {
  font-size: 12px;
}

.role-actions {
  display: flex;
  gap: 8px;
}

.action-btn {
  flex: 1;
  padding: 8px 12px;
  border: none;
  border-radius: 6px;
  font-size: 14px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.2s;
}

.action-btn.primary {
  background: linear-gradient(135deg, #667eea, #764ba2);
  color: white;
}

.action-btn.primary:hover {
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(102, 126, 234, 0.3);
}

.action-btn:not(.primary) {
  background: #f3f4f6;
  color: #374151;
  border: 1px solid #d1d5db;
}

.action-btn:not(.primary):hover {
  background: #e5e7eb;
}

.action-btn.danger {
  background: #fef2f2;
  color: #dc2626;
  border-color: #fecaca;
}

.action-btn.danger:hover {
  background: #fee2e2;
}

.action-btn.publish {
  background: #f0f9ff;
  color: #0369a1;
  border-color: #bae6fd;
}

.action-btn.publish:hover {
  background: #e0f2fe;
}

.action-btn.published {
  background: #f0fdf4;
  color: #166534;
  border-color: #bbf7d0;
  cursor: not-allowed;
}

.action-btn.unpublish {
  background: #fef3c7;
  color: #92400e;
  border-color: #fde68a;
}

.action-btn.unpublish:hover {
  background: #fde68a;
}

.empty-state {
  text-align: center;
  padding: 80px 20px;
  color: #6b7280;
}

.empty-icon {
  font-size: 4rem;
  margin-bottom: 16px;
}

.empty-state h3 {
  font-size: 1.5rem;
  font-weight: 600;
  color: #374151;
  margin-bottom: 8px;
}

.loading-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(350px, 1fr));
  gap: 24px;
}

.skeleton {
  background: white;
  border-radius: 16px;
  padding: 24px;
  box-shadow: 0 4px 6px rgba(0,0,0,0.05);
  border: 1px solid #e5e7eb;
}

.skeleton-avatar {
  width: 80px;
  height: 80px;
  border-radius: 50%;
  background: #e5e7eb;
  margin-bottom: 16px;
  animation: pulse 2s infinite;
}

.skeleton-content {
  flex: 1;
}

.skeleton-title {
  height: 20px;
  background: #e5e7eb;
  border-radius: 4px;
  margin-bottom: 8px;
  animation: pulse 2s infinite;
}

.skeleton-desc {
  height: 16px;
  background: #e5e7eb;
  border-radius: 4px;
  animation: pulse 2s infinite;
}

@keyframes pulse {
  0%, 100% { opacity: 1; }
  50% { opacity: 0.5; }
}

@media (max-width: 768px) {
  .roles-grid {
    grid-template-columns: 1fr;
  }
  
  .role-actions {
    flex-direction: column;
  }
  
  .role-stats {
    flex-direction: column;
    gap: 8px;
  }
}
</style>
